import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:toast/toast.dart';

class B2COBLPNSubmitScreen extends StatelessWidget {
  String obLpn;

  B2COBLPNSubmitScreen({this.obLpn});

  @override
  Widget build(BuildContext context) {
    return B2COBLPNSubmitScreenPage(obLpn: obLpn);
  }
}

class B2COBLPNSubmitScreenPage extends StatefulWidget {
  String obLpn;

  B2COBLPNSubmitScreenPage({this.obLpn});

  @override
  _B2COBLPNSubmitPageState createState() => _B2COBLPNSubmitPageState(obLpn: obLpn);
}

class _B2COBLPNSubmitPageState extends BaseState<B2COBLPNSubmitScreen> {
  String obLpn;
  String trkList = "Trackings List(0)";
  List<String> data = new List();

  _B2COBLPNSubmitPageState({this.obLpn});

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "OutBoundLPN: Tracking";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      next = "Submit";
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "OBLPN: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                child: Text(
                  Utils.getStringisEmpty(obLpn),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 35),
            child: TextField(
              controller: textEditingController,
              textInputAction: TextInputAction.search,
              onSubmitted: (String text) {
                print('Searching for $text');
                if (Utils.isEmpty(text)) {
                  return;
                }
                getLpnPhotoInfo(text);
              },
              // autofocus: true,
              decoration: InputDecoration(
                suffixIcon: IconButton(
                  padding: EdgeInsets.all(2.0),
                  icon: Icon(
                    Icons.qr_code_scanner,
                    size: 28,
                    color: MyAppTheme.nearlyBlue,
                  ),
                  onPressed: () {
                    // requestPermissions();
                    // Utils.scanBarcode(context);
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                      return ScanCode();
                    })).then((text) {
                      if (text == null) {
                        return;
                      }
                      setState(() {
                        textEditingController.text = text;
                      });
                      print(text); //拿到扫描结果
                      getLpnPhotoInfo(text);
                    });
                  },
                ),
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: MyAppTheme.nearlyBlue,
                  ),
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点之外的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点时的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                hintText: "scan trk#",
                filled: true,
                fillColor: MyAppTheme.white,
                //隐藏下划线
                //border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.grey),
                contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
              ),
              onChanged: (text) {
                code = text;
              },
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Text(
            Utils.getStringisEmpty(trkList),
            style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
          ),
          SizedBox(
            height: 5,
          ),
          Expanded(child: setListView())
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        String trk = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Text(
                      Utils.getStringisEmpty(trk),
                      style: MyAppTheme.test12,
                    )),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      data.removeAt(index);
                      trkList = "Trackings List(${data.length})";
                    });
                  },
                  child: Icon(
                    Icons.delete,
                    size: 20,
                    color: MyAppTheme.grey,
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void getLpnPhotoInfo(String trackingCode) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["obLpn"] = obLpn;
    map["trackingCode"] = trackingCode;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.checkTrackingCode, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      checkCode(trackingCode);
    } else if (baseResponse.status == 2208) {
      showDialog(
        context: context,
        builder: (context) => CustomDialog(),
      ).then((value) => {
            if ((value != null) && value) {checkCode(trackingCode)}
          });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void obBoundedTrackingCode() async {
    updateHint('');

    BoundedTracking boundedTracking = new BoundedTracking();
    boundedTracking.obLpn = obLpn;
    boundedTracking.trackingCodes = data;

    String json = jsonEncode(boundedTracking);
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.obBoundedTrackingCode, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      Navigator.of(context).pop(true);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void checkCode(String trackingCode) {
    bool isContain = false;
    for (int i = 0; i < data.length; i++) {
      if (trackingCode == data[i]) {
        isContain = true;
        i = data.length;
      }
    }

    if (!isContain) {
      setState(() {
        textEditingController.text = "";
        data.add(trackingCode);
        trkList = "Trackings List(${data.length})";
      });
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    // if (Utils.isEmpty(textEditingController.text)) {
    //   ToastContext().init(context);
    //   Toast.show("scan inbound lpn barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
    //   return;
    // }
    obBoundedTrackingCode();
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}

class CustomDialog extends StatefulWidget {
  @override
  _CustomDialogState createState() => _CustomDialogState();
}

class _CustomDialogState extends State<CustomDialog> {
  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("Other pick lists for this SKU need to be completed before handling its \"None Location\" sub-pick list.", style: MyAppTheme.textred14),
            SizedBox(height: 16.0),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(false);
                      },
                    )),
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Confirm',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(true);
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

class BoundedTracking {
  String obLpn;
  List<String> trackingCodes;

  Map<String, dynamic> toJson() {
    return {
      "obLpn": this.obLpn,
      "trackingCodes": this.trackingCodes,
    };
  }
}
